﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class PlayerControllerScript : MonoBehaviour
{
    public bool isGrounded;

    public LayerMask platforms;
    public Transform groundCheck;

    public float jumpPower;
    public float speed;
    public float health;
    public int maxHealth;

    public float checkRadius;
    public float maxVelocity;
    public Vector2 playerVel;

    private Rigidbody2D rb;
    Vector3 touchPosWorld;
    Vector3 mousePosWorld;

    GameObject HealthBar;

    void Awake()
    {
        Physics2D.IgnoreLayerCollision(9, 11);
    }

    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        HealthBar = GameObject.Find("HealthBar");
        health = maxHealth = 50;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, platforms);
        rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxVelocity);

        playerVel = rb.velocity;


        if (transform.position.x <= -2.6f)
        {
            transform.position = new Vector3(-2.59f, transform.position.y, transform.position.z);
        }

        if (transform.position.x >= 2.6)
        {
            transform.position = new Vector3(2.59f, transform.position.y, transform.position.z);
        }

    }

    public void JumpPlayer()
    {
        if (isGrounded && rb.velocity.y <= 0.25f && rb.velocity.y >= -0.25f)
        {
            rb.velocity = new Vector2(0, 0);
            rb.angularVelocity = 0;
            rb.AddForce(new Vector2(0, jumpPower));
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == "Enemy")
        {
            health -= col.GetComponent<EnemyControllScript>().enemyDamage;
            HealthBar.GetComponent<Scrollbar>().size = health / maxHealth;
        }
        else if (col.gameObject.tag == "DungDoor")
        {
            GameObject.Find("DungeonButton").GetComponent<Button>().interactable = true;
        }
    }

    void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "DungDoor")
        {
            GameObject.Find("DungeonButton").GetComponent<Button>().interactable = false;
        }
    }
}

